# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jhkim

from absl import app, flags
import pandas
import coin.exchange.base.kr_rest.native_public_client_base as npubcb

flags.DEFINE_string('input_csv', '', '')

flags.DEFINE_string('exchanges', '', '')

flags.DEFINE_string('base_currencies', '', '')

flags.DEFINE_integer('duration_in_hour', None, '')

flags.DEFINE_integer('exec_frequency_in_sec', None, '')


# this bans the ip...
class CoinmarketcapPublicClient(npubcb.NativePublicClientBase):
  def __init__(self):
    npubcb.NativePublicClientBase.__init__(self, url="https://api.coinmarketcap.com/v2")
    listings = self._get_as_json("listings").msg["data"]
    self._currency_dict = {}
    for listing in listings:
      self._currency_dict[listing['symbol']] = listing

  def get_currency_info(self, base_currency, quote_currency):
    assert base_currency in self._currency_dict, base_currency
    tickerinfo = self._get_as_json("ticker/%s?convert=%s" %
                                   (self._currency_dict[base_currency]['id'], quote_currency)).msg
    return tickerinfo['data']

  def get_24h_volume(self, base_currency, quote_currency):
    return self.get_currency_info(base_currency,
                                  quote_currency)['quotes'][quote_currency]['volume_24h']

  def queryAll(self, currency):
    pass


def main(_):
  sched = pandas.read_csv(flags.FLAGS.input_csv)
  assert len(flags.FLAGS.exchanges) > 0, flags.FLAGS.exchanges
  assert len(flags.FLAGS.base_currencies) > 0, flags.FLAGS.base_currencies
  exchanges = flags.FLAGS.exchanges.split(",")
  assert len(exchanges) > 0
  base_currency_list = flags.FLAGS.base_currencies.split(",")
  assert len(base_currency_list) > 0
  cpc = CoinmarketcapPublicClient()
  targets = []
  for _, target in sched.transpose().items():
    vol_in_usd = int(cpc.get_24h_volume(target['base_currency'], 'USD'))
    vol_in_btc = cpc.get_24h_volume(target['base_currency'], 'BTC')
    vol_in_base = int(cpc.get_24h_volume(target['base_currency'], target['base_currency']))
    target['info_vol_in_usd'] = vol_in_usd
    target['info_vol_in_btc'] = vol_in_btc
    target['info_vol_in_base'] = vol_in_base
    target['info_expected_num_of_fill'] = (flags.FLAGS.duration_in_hour * 3600
                                           / flags.FLAGS.exec_frequency_in_sec)
    target['info_duration_hour'] = flags.FLAGS.duration_in_hour
    target['info_market_volcon'] = (target['execution_qty'] /
                                    (flags.FLAGS.duration_in_hour / 24.0)) / vol_in_base
    target['average_lot_size'] = (target['execution_qty'] / target['info_expected_num_of_fill'])
    targets.append(target)
  print(pandas.DataFrame(targets).to_string())
  print(pandas.DataFrame(targets).to_csv())
  return 0


if __name__ == '__main__':
  app.run(main)
